using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Lzfy_His_Service.Models;
using Lzfy_His_Service.Services;
using System.ComponentModel.DataAnnotations;

namespace Lzfy_His_Service.Controllers
{
    /// <summary>
    /// 通话记录管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class CallLogController : ControllerBase
    {
        private readonly ICallLogService _callLogService;
        private readonly ILogger<CallLogController> _logger;

        public CallLogController(ICallLogService callLogService, ILogger<CallLogController> logger)
        {
            _callLogService = callLogService;
            _logger = logger;
        }

        /// <summary>
        /// 根据ID获取通话记录
        /// </summary>
        /// <param name="id">通话记录ID</param>
        /// <returns>通话记录信息</returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<CallLog>> GetById([Required] int id)
        {
            try
            {
                var callLog = await _callLogService.GetByIdAsync(id);
                if (callLog == null)
                {
                    return NotFound($"Call log with id {id} not found");
                }
                return Ok(callLog);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting call log by id: {Id}", id);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 获取所有通话记录
        /// </summary>
        /// <returns>通话记录列表</returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<CallLog>>> GetAll()
        {
            try
            {
                var callLogs = await _callLogService.GetAllAsync();
                return Ok(callLogs);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting all call logs");
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 根据用户名获取通话记录
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>通话记录列表</returns>
        [HttpGet("by-username/{username}")]
        public async Task<ActionResult<IEnumerable<CallLog>>> GetByUsername([Required] string username)
        {
            try
            {
                var callLogs = await _callLogService.GetByUsernameAsync(username);
                return Ok(callLogs);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting call logs by username: {Username}", username);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 根据电话号码获取通话记录
        /// </summary>
        /// <param name="callPhone">电话号码</param>
        /// <returns>通话记录列表</returns>
        [HttpGet("by-phone/{callPhone}")]
        public async Task<ActionResult<IEnumerable<CallLog>>> GetByCallPhone([Required] string callPhone)
        {
            try
            {
                var callLogs = await _callLogService.GetByCallPhoneAsync(callPhone);
                return Ok(callLogs);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting call logs by call phone: {CallPhone}", callPhone);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 获取最近的通话记录
        /// </summary>
        /// <param name="minutes">分钟数</param>
        /// <returns>通话记录列表</returns>
        [HttpGet("recent")]
        public async Task<ActionResult<IEnumerable<CallLog>>> GetRecent([Required] int minutes = 60)
        {
            try
            {
                var callLogs = await _callLogService.GetRecentAsync(minutes);
                return Ok(callLogs);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting recent call logs for minutes: {Minutes}", minutes);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 分页查询通话记录
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="username">用户名（可选）</param>
        /// <param name="callPhone">呼叫电话（可选）</param>
        /// <param name="startDate">开始日期（可选）</param>
        /// <param name="endDate">结束日期（可选）</param>
        /// <returns>分页的通话记录列表</returns>
        [HttpGet("paged")]
        public async Task<ActionResult<CallLogQueryResponse>> GetPaged(
            int pageIndex = 1,
            int pageSize = 20,
            string? username = null,
            string? callPhone = null,
            DateTime? startDate = null,
            DateTime? endDate = null)
        {
            try
            {
                var response = await _callLogService.GetPagedAsync(pageIndex, pageSize, username, callPhone, startDate, endDate);
                return Ok(response);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting paged call logs");
                return StatusCode(500, "Internal server error");
            }
        }



        /// <summary>
        /// 创建通话记录
        /// </summary>
        /// <param name="request">创建请求</param>
        /// <returns>创建的通话记录ID</returns>
        [HttpPost("create")]
        public async Task<ActionResult<int>> Create([FromBody] CallLogCreateRequest request)
        {
            try
            {
                var id = await _callLogService.CreateAsync(request);
                return CreatedAtAction(nameof(GetById), new { id }, id);
            }
            catch (ArgumentNullException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating call log");
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 更新通话记录
        /// </summary>
        /// <param name="id">通话记录ID</param>
        /// <param name="request">更新请求</param>
        /// <returns>更新结果</returns>
        [HttpPut("{id}")]
        public async Task<ActionResult> Update([Required] int id, [FromBody] CallLogUpdateRequest request)
        {
            try
            {
                if (request.Id != id)
                {
                    return BadRequest("ID in URL does not match ID in request body");
                }

                var result = await _callLogService.UpdateAsync(id, request);
                if (!result)
                {
                    return NotFound($"Call log with id {id} not found");
                }

                return NoContent();
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating call log with id: {Id}", id);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 删除通话记录
        /// </summary>
        /// <param name="id">通话记录ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult> Delete([Required] int id)
        {
            try
            {
                var result = await _callLogService.DeleteAsync(id);
                if (!result)
                {
                    return NotFound($"Call log with id {id} not found");
                }

                return NoContent();
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting call log with id: {Id}", id);
                return StatusCode(500, "Internal server error");
            }
        }
    }
}